/**Copyright (C) 2011 Ron Coleman. Contact: ronncoleman@gmail.com

 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.

 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 **/

package bj.gui

import javax.swing.event.ChangeEvent
import scala.swing.SimpleGUIApplication
import scala.swing.event
import java.awt.event.ActionListener
import event.ButtonClicked
import scala.swing.Frame
import scala.swing.Label
import scala.swing._
import scala.swing.Button
import scala.swing.FlowPanel
import scala.swing.GridPanel
import scala.swing.Component
import java.awt.Dimension
import java.awt.Color
import scala.swing.TextField
import javax.swing.ImageIcon
import javax.swing.event.ChangeListener
import scala.swing.event.ActionEvent
import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
import bj.util.Config
import bj.actor._
import scala.actors.Actor._
import org.apache.log4j.PropertyConfigurator
import scala.actors.OutputChannel
import bj.util.Logs

/**
 * @author Vikram
 * Collect all the information form the user, 
 * validates it and take them to Player Table 
 **/

object LoginScreen extends SimpleGUIApplication with Logs {
  javax.swing.UIManager.setLookAndFeel(new NimbusLookAndFeel)
  PropertyConfigurator.configure("log4j.properties")

  /** Player Id */
  var pId: Int = 0
  
  /** Player Name */
  var playerName = "guest"
    
  /** Player BankRoll */  
  var bankRoll = 0.0
  
  /** Player Bet Amount */
  var betAmt = 0.0
  
  /** Shuffling seed for shoe */
  var seed = 1
  
  /** Port no for remote host */
  var PORT = 9000
  
  /** Remote host IP address */
  var SERVER = "localhost"

  def top = bjLogin

  /** Creating new Mainframe */
  val bjLogin = new MainFrame {
    println("Login window Opened")
    title = "Blackjack Login"
    minimumSize = new Dimension(300, 300)
    resizable = false

    /** Creating Object for TextField - BetAmount */
    object betAmount extends TextField { columns = 7 }
    
    /** Creating Object for TextField - BankRoll */
    object bankRol extends TextField { columns = 7 }
    
    /** Creating Object for TextField - IP Address */
    object ipAddress extends TextField { columns = 7 }
    
    /** Creating Object for TextField - Port Number */
    object portNumber extends TextField { columns = 7 }
    
    /** Creating Object for TextField - Player Name */
    object nameField extends TextField { columns = 7 }
    
    /** Creating Object for TextField - Shuffling Seed */
    object seedField extends TextField { columns = 7 }

    /** Creating EnterGameButton */
    val enterGameButton = new Button { text = " Enter Game " }
    
    /** Creating ExitGameButton */
    val exitGameButton = new Button { text = "   Exit Game  " }

    /** Creating Welcome Panel containing a label with welcome text */
    val welcomePanel = new FlowPanel() {
      contents += new Label {
        text = "Welcome to Blackjack! Please Enter the details below"
        foreground = new java.awt.Color(255, 255, 255)
      }
//      background = new Color(58, 129, 159)
      background = new Color(0, 0, 0)
    }
    
    /** Creating list of labels to place in between the labels to fill the gap */
    val nameLabel = new Label { text = " " }
    val bankLabel = new Label { text = " " }
    val betLabel = new Label { text = " " }
    val ipLabel = new Label { text = " " }
    val portLabel = new Label { text = " " }
    val seedLabel = new Label { text = " " }
    val button = new Label { text = " " }
    
    /** Creating New Label for Player Name */
    val nameL = new Label { text = "Enter Player name"; foreground = new java.awt.Color(255, 255, 255) }
    
    /** Creating New Label for BankRoll */
    val bank = new Label { text = "Initial Bankroll $"; foreground = new java.awt.Color(255, 255, 255) }
    
    /** Creating New Label for BetAmount */
    val bet = new Label { text = "Enter Bet Amount $"; foreground = new java.awt.Color(255, 255, 255) }
    
    /** Creating New Label for IP address */
    val ip = new Label { text = "Enter House IP address"; foreground = new java.awt.Color(255, 255, 255) }
    
    /** Creating New Label for Port no */
    val port = new Label { text = "Enter Port Number"; foreground = new java.awt.Color(255, 255, 255) }
    
    /** Creating New Label for Seed */
    val seeed = new Label { text = "Enter shuffle seed"; foreground = new java.awt.Color(255, 255, 255) }

    /** Creating Button panel to add both the buttons */
    val buttonPanel = new FlowPanel() {
      contents += enterGameButton
      contents += exitGameButton
//      background = new Color(58, 129, 159)
      background = new Color(0, 0, 0)
      vGap = 5
    }

    /** Creating New Login label panel and adding all the contents related to it */
    val loginLabelPanel = new BoxPanel(Orientation.Vertical) {
      preferredSize = new java.awt.Dimension(150, 210)
      contents += nameLabel
      contents += nameL
      contents += bankLabel
      contents += bank
      contents += betLabel
      contents += bet
      contents += seedLabel
      contents += seeed
      contents += ipLabel
      contents += ip
      contents += portLabel
      contents += port
      //background = new Color(58, 129, 159)
      background = new Color(0, 0, 0)
    }

    /** Creating New Login TextBox panel and adding all the contents related to it */
    val loginTextPanel = new BoxPanel(Orientation.Vertical) {
      preferredSize = new java.awt.Dimension(100, 190)
      contents += nameField
      contents += bankRol
      contents += betAmount
      contents += seedField
      contents += ipAddress
      contents += portNumber
      //background = new Color(58, 129, 159)
      background = new Color(0, 0, 0)
    }

    /** Creating New Login Flow and adding both Label and Textbox Panel */
    val loginFlow = new FlowPanel {
      contents += loginLabelPanel
      contents += loginTextPanel
      //background = new Color(58, 129, 159)
      background = new Color(0, 0, 0)
    }

    /** Creating New Login Deatils panel containing Welcome text, login details and Button panel */
    val loginDetailsPanel = new BoxPanel(Orientation.Vertical) {
      contents += welcomePanel
      contents += loginFlow
      contents += buttonPanel
      background = new Color(0, 0, 0)
    }

    /** Creating New Box Panel and adding a Image and Login Details panel */
    contents = new BoxPanel(Orientation.Horizontal) {
      contents += new Label { icon = new ImageIcon("images/bjwelcome.jpg") }
      contents += loginDetailsPanel

      border = Swing.EmptyBorder(20)
     // background = new Color(58, 129, 159)
      background = new Color(0, 0, 0)
    }

    listenTo(enterGameButton)
    listenTo(exitGameButton)
    reactions += {

      /** Creating Button Clieck event reactions for EnterGame Button, it validates and take them to next screen */
      case ButtonClicked(`enterGameButton`) => {
        println("Clicked enterGame button")

        var message = validateInputs()

        if (message.length == 0) {

          playerName = nameField.text
          println(playerName)
          bankRoll = bankRol.text.toDouble
          println(bankRoll)
          betAmt = betAmount.text.toDouble
          println(betAmt)
          seed = seedField.text.toInt
          println(seed)
          SERVER = ipAddress.text
          println(SERVER)
          PORT = portNumber.text.toInt
          println(PORT)

          new HumanGui
          visible = false
          this.close();

        } else {
          Dialog.showMessage(null, message, "Error", Dialog.Message.Error, new ImageIcon("images/bjzone.png"))
          visible = true
        }

      }

      /** Exit the window by closing */
      case ButtonClicked(`exitGameButton`) =>
        println("Clicked exitGame button")
        System.exit(0)
    }

    /** Validating input entered by the User and if any wrong input it prompts the user for correction */
    def validateInputs(): String = {

      var message = ""

      if (nameField.text == "") { message += " Enter Player Name" }

      else if (bankRol.text == "") { message += "\n Enter BankRoll Amount" }

      else if (betAmount.text == "") { message += "\n Enter Bet Amount" }

      else if (seedField.text == "") { message += "\n Enter Shuffle Seed 0-9" }

      else if (ipAddress.text == "") { message += "\n Enter House IP Address" }

      //      if (ipAddress.text != "localhost")
      //        if (ipAddress.text != "127.0.0.1") { message += "\n Enter House IP Address as localhost / 127.0.0.1" }

      else if (portNumber.text == "") { message += "\n Enter Port Number" }

      else if (portNumber.text != "9000") { message += "\n Enter Port Number as 9000" }

      var isBankrolNumeric = false
      try {
        bankRol.text.toDouble
        isBankrolNumeric = true
      } catch {
        case e: Exception => isBankrolNumeric = false
      }

      var isBetAmtNumeric = false
      try {
        betAmount.text.toDouble
        isBetAmtNumeric = true
      } catch {
        case e: Exception => isBetAmtNumeric = false
      }

      var isSeedNumeric = false
      try {
        seedField.text.toDouble
        isSeedNumeric = true
      } catch {
        case e: Exception => isSeedNumeric = false
      }

      try {

        if (betAmount.text.toDouble > bankRol.text.toDouble) { message += "\n Bet amount value should be less than bankroll" }
      } catch {
        case e: Exception => message += ""
      }

      if (!isSeedNumeric) { message += "\n Seed must be a numeric value" }

      else if (seedField.text.toDouble > 9) { message += "\n Maximum shuffle seed allowed is 9" }

      if (!isBankrolNumeric) { message += "\n Bankroll must be a numeric value." }

      else if (bankRol.text.toDouble > 10000) { message += "\n Maximum bankRol allowed is $10000" }

      if (!isBetAmtNumeric) { message += "\n Bet amount must be a numeric value" }

      else if (betAmount.text.toDouble < 5) { message += "\n Minimum bet amount allowed is $5" }

      else if (betAmount.text.toDouble > 200) { message += "\n Maximum bet amount allowed is $200" }
      message

    }
    centerOnScreen()
  }

}

